import moment from 'moment'
import Erc20 from '@/data/erc20abi.json'
import BigNumber from 'bignumber.js'

const timeAgo = (time1, time2 = moment(), flag) => {
	// let time2 = moment()
	const duration = moment.duration(moment(time2).diff(moment(time1)));
	// return 0
	let result = '';
	if (duration.days() > 0) {
		return `${duration.days()}day${duration.days() > 1 && 's'} ${flag ? '' : 'ago'}`;
	}
	if (duration.hours() > 0) {
		return `${duration.hours()}hr ${flag ? '' : 'ago'}`;
	}
	if (duration.minutes() > 0) {
		return `${duration.minutes()}min ${flag ? '' : 'ago'}`;
	}
	if (duration.seconds() > 0) {
		return `${duration.seconds()}s ${flag ? '' : 'ago'}`;
	}
	return result || '1s';
}

const subAddress = function (str, idx = 8) {
	if (str.length > 30) {
		return str.slice(0, idx) + '....' + str.substring(str.length - (idx - 2), str.length)
	} else {
		return str
	}
}
const subTx = function (str, idx = 10) {
	if (str.length > 20) {
		return str.slice(0, idx) + '...'
	} else {
		return str
	}
}

const math18 = function (str, dec) {
	if (str == null) {
		return '--'
	}
	// var a = (10000000000000000000000000000000000000000000000000000)
	// console.log((new BigNumber(a)).toFixed(2))
	let decimals = new BigNumber(str).dividedBy(Math.pow(10, parseInt(dec) || 18))
	// console.log(decimals.toFormat())
	// let i = decimals.toFormat().indexOf('.')

	// if (i > -1) {
	// 	let len = decimals.toFormat().length - i - 1
	// 	if (len > 8) {
	// 		return decimals.toFixed(8, 1)
	// 	}
	// }
	return decimals.toFormat()
}

const math18x = function (str, dec) {
	let decimals = new BigNumber(str).dividedBy(Math.pow(10, parseInt(dec) || 18))
	return decimals.toFormat()
}

const math = function (str) {
	let decimals = new BigNumber(str)
	return decimals.toFormat()
}

const utcTime = (timestamp) => {
	return moment(timestamp).utc().format('YYYY-MM-DD HH:mm:ss');
}

const onDownload = (list, name) => {
	// alert(111)
	console.log(list.length)
	if (list.length > 0) {
		// 将数据转换为CSV格式
		const csv = convertToCSV(list);

		// 创建一个Blob对象
		const blob = new Blob([csv], { type: 'text/csv' });

		// 创建一个下载链接
		const url = URL.createObjectURL(blob);

		// 创建一个<a>元素并设置下载链接
		const link = document.createElement('a');
		link.href = url;
		link.download = name ? name : 'transaction_data.csv';

		// 模拟点击下载链接
		link.click();

		// 释放URL对象
		URL.revokeObjectURL(url);
	} else {
		alert('NO DATA')
		return;
	}

}

const convertToCSV = (list) => {
	// 使用深拷贝
	let jsonArray = JSON.parse(JSON.stringify(list));
	jsonArray.map((item) => {
		if (item?.ts) {
			item.ts = utcTime(item.ts)
		}

		if (item?.success && item.success != undefined) {
			item.success = item.success ? 'success' : 'failed'
		}

		if (item?.value) {
			item.value = math18(item?.value, item?.decimals ? item.decimals : null).replace(',', '')
			console.log(item?.decimals ? item.decimals : null)
		}

	})
	const header = Object.keys(jsonArray[0]).map(key => `${key == 'success' ? 'state' : (key == 'ts' ? 'time' : key)}`).join(',') + '\n';
	console.log('header')
	console.log(header)
	const rows = jsonArray.map(obj => Object.values(obj).map(val => `="${val}"`).join(',')).join('\n');
	console.log('rows')
	console.log(rows)
	return header + rows;
}

const isContract = async (address) => {
	if (window.web3js) {
		let code = await window.web3js.eth.getCode(address)
		if (code === '0x') {
			return false
		} else {
			return true;
		}
	}
	return null
}

const blockTips = [
	"Also known as Block Number. The block height, which indicates the length of the blockchain, increases after the addition of the new block.",
	"The date and time at which a block is mined.",
	"The number of transactions in the block. Internal transaction is transactions as a result of contract execution that involves TOK value.",
	"Miner who successfully include the block onto the blockchain.",
	"For each block, the miner is rewarded with a finite amount of TOK on top of the fees paid for all transactions in the block.",
	"An uncle block has a significantly lower reward than a normal block. Uncles reward is valid but rejected as it is not on the longest chain which is the working mechanism of the blockchain. Uncle block is important in Moman Chain as it secures the blockchain.",
	"The amount of effort required to mine a new block. The difficulty algorithm may adjust according to time.",
	"Total difficulty of the chain until this block.",
	"The block size is actually determined by the block's gas limit.",
	"The total gas used in the block and its percentage of gas filled in the block.",
	"Total gas limit provided by all transactions in the block.",
	"Post-London Upgrade, this represents the minimum gasUsed multiplier required for a tx to be included in a block. ",
	"Post-London Upgrade, this represents the part of the tx fee that is burnt: baseFeePerGas * gasUsed",
	"Any data that can be included by the miner in the block.",
	"The hash of the block header of the current block.",
	"The hash of the block from which this block was generated, also known as its parent block.",
	"The mechanism which Tok Chain Javascript RLP encodes an empty string.",
	"The root of the state trie",
	"Block nonce is a value used during mining to demonstrate proof of work for a block.",
];

const txTips = [
	"A TxHash or transaction hash is a unique 66-character identifier that is generated whenever a transaction is executed.",
	"The status of the transaction.",
	"Number of the block in which the transaction is recorded. Block confirmations indicate how many blocks have been added since the transaction was mined.",
	"The date and time at which a transaction is mined.",
	"The sending party of the transaction.",
	"The receiving party of the transaction (could be a contract address).",
	"List of token transferred in the transaction.",
	"The value being transacted in TOK and fiat value. Note: You can click the fiat value (if available) to see historical value at the time of transaction.",
	"Amount paid to the miner for processing the transaction.",
	"Cost per unit of gas specified for the transaction, in TOK and Gwei. The higher the gas price the higher chance of getting included in a block.",
	"Maximum amount of gas allocated for the transaction & the amount eventually used. Normal TOK transfers involve 21,000 gas units while contracts involve higher values.",
	"Base Fee refers to the network Base Fee at the time of the block, while Max Fee & Max Priority Fee refer to the max amount a user is willing to pay for their tx & to give to the miner respectively.",
	"Total amount of TOK burnt from this tx & total fees saved from the amount the user was willing to pay for this tx.",
	"Other data related to this transaction.",
	"Additional data included for this transaction. Commonly used as part of contract interaction or as a message sent to the recipient.",

];

// const sortFieldMatch = (field) => {
// 	if (field == 'TokensTransferred') {
// 		// debugger
// 	}
// 	if (field === undefined) return;
// 	const stringArray = field.split('') // 将字符串分割成相应的字符串数组
// 	let newField = field
// 	stringArray.forEach((t, i) => {
// 		if (/[A-Z]/.test(t) && i !== 0) {
// 			// 遍历分割之后的字符串组，将找到的大写字母替换成其他字符串，将替换后的字符串赋值给另外一个新的string 变量
// 			newField = newField.replaceAll(t, `\u00a0${t}`);
// 			// debugger
// 		}
// 	})
// 	return newField
// }
function sortFieldMatch(str) {
	// 正则表达式：在大写字母前加空格，忽略字符串的第一个字母
	return str.replace(/([A-Z])/g, ' $1').trim();
}

const abiContract = async function (address, type) {
	if (window.web3js) {
		let myCont = new window.web3js.eth.Contract(Erc20, address);
		console.log('myCont')
		console.log(myCont)
		try {
			if (type === 'name') {
				let name = await myCont.methods.name().call()
				return name
			} else if (type === 'symbol') {
				let symbol = await myCont.methods.symbol().call()
				// console.log('symbol')
				// console.log(symbol)
				return symbol
			} else if (type === 'decimals') {
				let decimals = await myCont.methods.decimals().call()
				return decimals
			}
		} catch (err) {
			// alert('The ' +type+ ' is empty')
		}
	}
}

export {
	timeAgo,
	subAddress,
	math18,
	subTx,
	onDownload,
	utcTime,
	math,
	math18x,
	sortFieldMatch,
	isContract,
	abiContract,
	blockTips,
	txTips
}
